<?php

namespace app\user\controller;
use app\common\controller\UserBase;
use think\Request;
use app\common\model\WeixinUser;

class Weixin extends UserBase
{
    protected $noLogin = ['login','get_userinfo', 'bangding', 'captcha_sms'];
    protected function _initialize()
    {
        parent::_initialize();
        !config('website_status') && die(config('colse_explain'));
        $config = cache('db_config_data');
        if (!$config) {
            $config = [];
            foreach (model('config')->select() as $v) {
                $config[$v['group']][$v['name']] = $v['value'];
            }
            cache('db_config_data', $config);
        }
        config($config);
    }
    //微信登陆
    public function login()
    {
        $type = input('type');
        $wx = include(__DIR__ ."/../../setting.php");
        $appid = $wx['weixin']['appid'];
        $appsecret = $wx['weixin']['appsecret'];
        if($type=='bangding'){//后台绑定
            $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.urlencode($this->request->domain().'/user/weixin/bangding').'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        }else{
            $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.urlencode($this->request->domain().'/user/weixin/get_userinfo').'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        }
        $this->redirect($url);        
    }
    //获取微信基本资料
    public function get_userinfo()
    {
        $wx = include(__DIR__ ."/../../setting.php");
        $appid = $wx['weixin']['appid'];
        $appsecret = $wx['weixin']['appsecret'];
        $code = input('code');
        //拉取基本信息
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        $res= https_request($get_token_url);
        $json_obj = json_decode($res,true);
        //检查openid
        $wxuser = WeixinUser::get_userinfo($json_obj['openid'],$json_obj['access_token']);
        if($wxuser['uid']=='0'){
            session('openid', $json_obj['openid']);
            $this->redirect('user/weixin/bangding_login');
        }else{
            $admin = model('user')->get($wxuser['uid']);
            //检查是否到期
            if($admin['shop_id']!='0'){
                $shop = model('shop')->get($admin['shop_id']);
                if(strtotime($shop['exp_time']) < time()){
                    $this->error('您的软件服务已到期，请续费');
                }else{
                    if($shop['admin_id']==$admin['id']){
                        session('user_admin','1');
                    }
                }
            }
            $admin['status'] != 1 && $this->error('账号已禁用');
            // 保存状态
            $auth = [
                'user_id' => $admin['id'],
                'shop_id' => $admin['shop_id'],
                'username' => $admin['username'],
                'realname' => $admin['realname'],
            ];
            session('user_auth', $auth);
            session('user_auth_sign', data_auth_sign($auth));
            // 更新信息
            model('user')->save([
                'last_login_time' => time(),
                'last_login_ip'   => $this->request->ip(),
                'login_count'     => $admin['login_count'] + 1,
            ], ['id' => $admin['id']]);
            insert_user_log('使用微信登录了后台系统');
            $this->redirect('user/index/index');
        }
    }
    //微信绑定
    public function bangding_login()
    {
        $openid = session('openid');
        $wxuser = model('weixinUser')->where(['openid'=>$openid])->find();
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = $this->validate($param, 'login_mobile');
            if ($result !== true) {
                $this->error($result);
            }
            //验证用户名是否手机号码
            if(check_mobile($param['username']) == true){
                $admin = model('user')->where(['mobile' => $param['username'],'password' => md5($param['password'])])->find();
            }else{
                $admin = model('user')->where(['username' => $param['username'],'password' => md5($param['password'])])->find();
            }
            //绑定账号
            model('user')->where(['id'=>$admin['id']])->update(['openid'=>$openid]);
            model('weixinUser')->where(['openid'=>$openid])->update(['uid'=>$admin['id']]);
            if ($admin) {
                //检查是否到期
                if($admin['shop_id']!='0'){
                    $shop = model('shop')->get($admin['shop_id']);
                    if(strtotime($shop['exp_time']) < time()){
                        $this->error('您的软件服务已到期，请续费');
                    }else{
                        if($shop['admin_id']==$admin['id']){
                            session('user_admin','1');
                        }
                    }
                }
                $admin['status'] != 1 && $this->error('账号已禁用');
                // 保存状态
                $auth = [
                    'user_id' => $admin['id'],
                    'shop_id' => $admin['shop_id'],
                    'username' => $admin['username'],
                    'realname' => $admin['realname'],
                ];
                session('user_auth', $auth);
                session('user_auth_sign', data_auth_sign($auth));
                // 更新信息
                model('user')->save([
                    'last_login_time' => time(),
                    'last_login_ip'   => $this->request->ip(),
                    'login_count'     => $admin['login_count'] + 1,
                ], ['id' => $admin['id']]);
                insert_user_log('登录了后台系统');
                $this->success('登录成功', url('user/index/index'));
            } else {
                $this->error('账号或密码错误');
            }
        }
        return $this->fetch('bangding_login',[
            'wxuser' => $wxuser,
        ]);
    }
    //获取微信基本资料
    public function bangding()
    {
        $wx = include(__DIR__ ."/../../setting.php");
        $appid = $wx['weixin']['appid'];
        $appsecret = $wx['weixin']['appsecret'];
        $code = input('code');
        //拉取基本信息
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        $res= https_request($get_token_url);
        $json_obj = json_decode($res,true);
        //检查openid
        $wxuser = WeixinUser::get_userinfo($json_obj['openid'],$json_obj['access_token']);
        if($wxuser['uid']=='0'){
            session('openid', $json_obj['openid']);
            //更新用户表
            model('user')->where(['id'=>session('user_auth.user_id')])->update(['openid'=>$json_obj['openid']]);
            //更新微信表
            model('weixinUser')->where(['openid'=>$json_obj['openid']])->update(['uid'=>session('user_auth.user_id')]);
            $this->success('绑定成功', url('user/index/info'));
        }else{
            $this->error('该微信已经绑定了其他账号。');
        }
    }
    
    
    
    
    
}
